package com.tyut.musicdreamer.service.music.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web安全配置
 * 从请求头中读取用户ID，并设置到请求属性中
 */
@Configuration
@Slf4j
public class WebSecurityConfig implements WebMvcConfigurer {

    private static final String USER_ID_HEADER = "X-User-Id";
    private static final String USER_ROLE_HEADER = "X-User-Role";
    private static final String USER_ID_ATTRIBUTE = "userId";
    private static final String USER_ROLE_ATTRIBUTE = "userRole";

    /**
     * 创建用户ID拦截器，从请求头读取用户ID并设置到请求属性中
     * 如果请求头中没有用户ID，则不设置默认值，由各个控制器自行处理
     */
    @Bean
    public HandlerInterceptor userIdInterceptor() {
        return new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                // 从请求头中获取用户ID
                String userIdHeader = request.getHeader(USER_ID_HEADER);
                String userRoleHeader = request.getHeader(USER_ROLE_HEADER);
                
                log.debug("处理请求: {}, 路径: {}, 用户ID头: {}, 角色头: {}", 
                          request.getMethod(), request.getRequestURI(), 
                          userIdHeader, userRoleHeader);
                
                // 如果请求头中有用户ID，则设置到请求属性中
                if (StringUtils.hasText(userIdHeader)) {
                    try {
                        Long userId = Long.parseLong(userIdHeader);
                        request.setAttribute(USER_ID_ATTRIBUTE, userId);
                        log.debug("设置用户ID到请求属性: {}", userId);
                    } catch (NumberFormatException e) {
                        log.warn("请求头中的用户ID不是有效的数字: {}", userIdHeader);
                    }
                }
                
                // 设置用户角色
                if (StringUtils.hasText(userRoleHeader)) {
                    request.setAttribute(USER_ROLE_ATTRIBUTE, userRoleHeader);
                }
                
                return true;
            }
        };
    }
    
    /**
     * 添加用户ID拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userIdInterceptor())
                .addPathPatterns("/**");
        log.info("添加用户ID拦截器，从请求头读取用户ID并设置到请求属性中");
    }
} 